let express = require('express')

let router = express.Router()

let {
    conMysql
} = require('../mysql')

// 获取分区信息
router.get('/getInfoArea', (req, res) => {
    let sql = 'select * from info_area'
    let params = []
    conMysql(sql, params).then(result => {
        let data = {
            code: 0,
            data: result,
            msg: 'success'
        }
        res.send(data)
    })
})

// 删除
router.delete('/deleteInfoArea', (req, res) => {
    let sql = `delete from info_area where ID = ? `
    let params = req.body.ID
    conMysql(sql, params).then(result => {
        let data = {
            code: 0,
            msg: '删除成功!'
        }
        res.send(data)
    }).catch(err => {
        let data = {
            code: 1,
            msg: '删除失败'
        }
        res.send(data)
    })
})

// 新增
router.post("/addInfoArea", (req, res) => {
    const sql = "insert into info_area (Name,Side,Start,End,Type,Color) values (?,?,?,?,?,?)";
    let reqObj = JSON.parse(JSON.stringify(req.body))
    delete reqObj.ID
    let params = Object.values(reqObj);
    conMysql(sql, params).then((data) => {
        res.send(data);
    }).catch(err => {

        res.status(500).send('数据库连接出错!')
    })
});

// 修改
router.post("/editInfo", (req, res) => {

    let sql = `update info_area set password = '${req.body.newPassword}' where username = '${req.body.username}'`
    conMysql(sql).then(result => {
        if (result.affectedRows == 1) {
            let response = new Response(true, '修改成功', 200, result)
            res.send(response)
        } else {
            let response = new Response(false, '修改失败,请联系开发者解决')
            res.status(400).send(response)
        }
    }).catch(err => {
        res.status(500).send('数据库连接出错!')
    })
});

module.exports = router